package timing.ukulele.util;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.User;

import javax.crypto.spec.SecretKeySpec;
import javax.xml.bind.DatatypeConverter;
import java.security.Key;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.Date;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

public final class JWtUtil {
    private static Key getKeyInstance(String salt) {
        SignatureAlgorithm signatureAlgorithm = SignatureAlgorithm.HS256;
        String apiKey = DatatypeConverter.printBase64Binary(salt.getBytes());
        byte[] apiKeySecretBytes = DatatypeConverter.parseBase64Binary(apiKey);
        SecretKeySpec secretKeySpec = new SecretKeySpec(apiKeySecretBytes, signatureAlgorithm.getJcaName());
        return secretKeySpec;
    }

    public static String createJavaWebToken4JwtAuth(Map<String, Object> claims, String salt, Integer exp) {
        String token = Jwts.builder().setClaims(claims).setExpiration(DateAdd(exp)).signWith(SignatureAlgorithm.HS256, getKeyInstance(salt)).compact();
        return token;
    }

    public static Map<String, Object> verifyJavaWebToken(String token, String salt) {
        Map<String, Object> body = Jwts.parser().setSigningKey(getKeyInstance(salt)).parseClaimsJws(token).getBody();
        return body;
    }

    public static Authentication getAuthentication(String token, String salt) {
        Map<String, Object> body = verifyJavaWebToken(token, salt);
        if (body == null || body.get("user-info") == null) {
            return null;
        }
        LinkedHashMap<String, Object> userDetails = (LinkedHashMap) body.get("user-info");
        List<GrantedAuthority> authorities = userDetails == null ? AuthorityUtils.NO_AUTHORITIES : AuthorityUtils.commaSeparatedStringToAuthorityList(String.valueOf(userDetails.get("role")));
        User principal = new User((String) userDetails.get("username"), "", authorities);
        return new UsernamePasswordAuthenticationToken(principal, token, authorities);
    }

    private static Date DateAdd(Integer exp) {
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime result = now.plus(exp, ChronoUnit.MICROS);
        Instant instant = result.atZone(ZoneId.systemDefault()).toInstant();
        Date expireAt = Date.from(instant);
        return expireAt;
    }
}
